package com.example.wacoffee_manage.websocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.wacoffee_manage.vo.message;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/websocket/{clientId}")
public class WebSocketServer {


    private static Map<String, Session> sessionMap=new HashMap<>();
    @OnOpen
    public void onOpen(Session session,@PathParam("clientId") String clientId) throws IOException {
        System.out.println("连接成功:"+clientId);
        sessionMap.put(clientId, session);
    }
    @OnMessage
    public void onMessage(String message,@PathParam("clientId") String clientId) throws IOException {
        Session session=sessionMap.get(clientId);
        session.getAsyncRemote().sendText("收到消息:"+message);
        JSONObject entries = JSONUtil.parseObj(message);
        if(entries.isEmpty())return;
        String orderId = entries.getStr("orderId");
        String action = entries.getStr("action");
        sendMessage(orderId,action);
    }
    @OnClose
    public void onClose(@PathParam("clientId") String clientId) {
        System.out.println("连接断开:" + clientId);
        sessionMap.remove(clientId);
    }
    public static void sendMessage() throws IOException {
        for(String key:sessionMap.keySet())
        {
            Session session=sessionMap.get(key);
            if(session!=null){
                session.getBasicRemote().sendText("有新的订单请尽快查收");
                System.out.println("发送成功");
            }
        }
    }

    public static void sendMessage(String orderId,String action) throws IOException {
       for(String key:sessionMap.keySet()){
           if(key.equals("management-client")){
               Session session=sessionMap.get(key);
               if(session!=null){
                   session.getBasicRemote().sendText("有新的订单请尽快查收");
                   System.out.println("发送成功");
               }
           }
           else if(key.equals(orderId)){
               Session session=sessionMap.get(key);
               if(session!=null){
                   session.getBasicRemote().sendText(new message(orderId,action).toString());
                   System.out.println("发送成功");
               }
           }
       }
    }
}
